package main

import (
	"bufio"
	"fmt"
	"go-guide/outersort/pipeline"
	"os"
)

func main() {
	generateData()
}

func generateData() {
	const (
		filename = "large.in"
		n        = 1000000000
	)

	file, err := os.Create(filename)
	if err != nil {
		panic(err)
	}
	defer file.Close()
	p := pipeline.RandomSource(n)
	// 使用bufio可以大幅度的提升生成速度
	// 避免每次写都要flush到磁盘, 而是批量的冲刷到磁盘上, 避免多次IO操作
	writer := bufio.NewWriter(file)
	defer writer.Flush()

	pipeline.WriterSink(writer, p)

	file, err = os.Open(filename)
	if err != nil {
		panic(err)
	}

	defer file.Close()
	p = pipeline.ReaderSource(bufio.NewReader(file), -1)

	count := 0
	for v := range p {
		fmt.Println(v)
		count++
		if count >= 100 {
			break
		}
	}
}

func mergerDemo() {
	p := pipeline.Merge(
		pipeline.InMemorySort(pipeline.ArraySource(1, 3, 2, 5, 8, 7)),
		pipeline.InMemorySort(pipeline.ArraySource(12, 23, 22, 15, 0, 7)))

	for {
		if num, ok := <-p; ok {
			fmt.Println(num)
		} else {
			break
		}
	}
}
